在一個.java檔案裡面可以包含多個 class,但有以下幾個規則:
公開類別 (public class):
public class Main,那麼檔案名稱必須是 Main.java。非公開類別 (non-public classes):
Java的Class可以包含以下五個元素:
Car)時會執行。Engine:可以訪問外部類的 brand 屬性,並且有一個方法 start()。Vehicle:定義一個 accelerate() 方法,並在外部類中通過 CarVehicle 類實現這個介面。// Outer class
public class Car {
    // 1. Fields (欄位)
    private String brand;
    private int year;
    
    // Static field (靜態欄位)
    private static int carCount;
    // 2. Constructors (建構子)
    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
        carCount++;
    }
    // 3. Methods (方法)
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public int getYear() {
        return year;
    }
    public void setYear(int year) {
        this.year = year;
    }
    public void drive() {
        System.out.println(brand + " is driving.");
    }
    // Static method (靜態方法)
    public static int getCarCount() {
        return carCount;
    }
    // 4. Blocks (區塊)
    // Instance initialization block (實例初始化區塊)
    {
        System.out.println("A new Car object is being created!");
    }
    // Static block (靜態區塊)
    static {
        carCount = 0; // 初始化靜態變量
        System.out.println("Static block: Car class loaded.");
    }
    // 5. Nested class and interface (內部類別和介面)
    // Nested class
    public class Engine {
        public void start() {
            System.out.println(brand + "'s engine is starting.");
        }
    }
    // Nested interface
    public interface Vehicle {
        void accelerate();
    }
    // Implementing the nested interface within the outer class
    public class CarVehicle implements Vehicle {
        @Override
        public void accelerate() {
            System.out.println(brand + " is accelerating.");
        }
    }
}
使用範例
public class Main {
    public static void main(String[] args) {
        // 創建 Car 物件
        Car myCar = new Car("Toyota", 2022);
        myCar.drive();  // 輸出: Toyota is driving.
        // 使用內部類 Engine
        Car.Engine engine = myCar.new Engine();
        engine.start();  // 輸出: Toyota's engine is starting.
        // 使用內部介面的實現
        Car.CarVehicle vehicle = myCar.new CarVehicle();
        vehicle.accelerate();  // 輸出: Toyota is accelerating.
        // 獲取 Car 物件的總數
        System.out.println("Total cars: " + Car.getCarCount());
    }
}